/*
Class Name:OverrideMaterialEdit
Function: override Material Edit Button, according to UI(Material Allocation)
Author: Shuai Cao(shuaicao@isoftstone.com)
*/

with sharing public class OverrideMaterialEdit
{
    public String IdSelect{get;set;}
    public String msg{get;set;}
    public String msg1{get;set;}
    Decimal total = 0;
    Set<Material__Share> MatShare = new Set<Material__Share>();
 
    
     public Material__c Mat{
         get{
             if(Mat == null)
                 Mat = new Material__c();
             return Mat;
         }
         set;
     }
     public List<HospitalMaterial__c> HosMatList{
         get{
             if(HosMatList== null)
                 HosMatList= new List<HospitalMaterial__c>();
             return HosMatList;         
         }
         set;
     }
     public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');
        }  
        set;
    }   

     
    public OverrideMaterialEdit(ApexPages.StandardController controller){
        this.controller=controller;
        
        total = 0;
        List<HospitalMaterial__c> loopHMList = new List<HospitalMaterial__c>();
        Mat = [Select id,Comment__c,City__c,Date__c,Material__c,Materical_End_Date__c,Materical_Start_Date__c,Total_Number__c,AllocatedNumber__c From Material__c Where id =: UrlId];
        
        List<HospitalMaterial__c> haveHM = new List<HospitalMaterial__c>();
        haveHM = [Select HospitalActive__c, HospitalClass__c,CreatedDate,MSR__c,City__c,Number__c,Hospital__c,Hospital__r.name,Hospital_Class__c,name, Hospital__r.approvalstatus__c,
                  Hospital__r.Active__c,ownerid,Hospital__r.ownerid From HospitalMaterial__c Where Material__c =: UrlId];
        
        List<Hospital__c> HosList = [Select id, Name,class__c,City__r.name,Active__c,ownerid From Hospital__c Where City__c =: Mat.City__c and 
                                    (Active__c =: true or approvalstatus__c =: GlobalProperties.ApprovedButNotEffective) order by ownerid];

       Set<Id> uIds = new Set<Id>(); 

       for(Hospital__c hos : HosList)
       {
           uIds.add(hos.ownerid);
       }
       List<User> uList = [Select id,Alias From User Where id in: uIds];
       for(Hospital__c hos : HosList)
       {
           for(User u : uList)
           {
               if(hos.ownerid == u.id)
               {
                   HospitalMaterial__c HM = new HospitalMaterial__c();
                   HM.ownerid = hos.ownerid;
                   HM.City__c = hos.City__r.name;
                   HM.Hospital__c = hos.id;
                   HM.Hospital_Class__c = hos.class__c;
                   HM.Name = hos.name;
                   HM.HospitalActive__c =hos.Active__c;
                   loopHMList.add(HM);
               }
           }
       }
       for(HospitalMaterial__c hm : haveHM)
       {       
           if((hm.Hospital__r.Active__c == false)&&(hm.Hospital__r.approvalstatus__c == null))
           {
                hm.name = hm.Hospital__r.name;
                hm.HospitalActive__c = false;
                hm.ownerid = hm.Hospital__r.ownerid;
                HosMatList.add(hm);           
           }
       }
       for(HospitalMaterial__c hml: loopHMList)
       {
           Boolean haveFlag = false;
           for(HospitalMaterial__c hm : haveHM)
           {
               if(hml.Hospital__c == hm.Hospital__c)
               {
                    hm.name = hm.Hospital__r.name;
                    hm.ownerid = hml.ownerid;
                    hm.Hospital_Class__c = hml.Hospital_Class__c;
                    hm.HospitalActive__c = hml.HospitalActive__c;
                    HosMatList.add(hm);
                    haveFlag = true;
               }

           }
           if(haveFlag == false)
           {
               HosMatList.add(hml);
           }
       }     
    }
    
    public PageReference Save()
    {
        if(HosMatList != null){
            for(HospitalMaterial__c hm : HosMatList)
            {
                if((hm.Number__c != 0)&&(hm.Number__c != null)){
                    total += hm.Number__c;
                }
            }
        } 

        if(Mat.Materical_Start_Date__c == null)
        {
            msg = '物料开始日期不能为空';
            Mat.AllocatedNumber__c = total;
            total=0;
            return null;
        }
        if(Mat.Materical_End_Date__c == null)
        {
            msg = '物料结束日期不能为空';
            Mat.AllocatedNumber__c = total;
            total=0;
            return null;
        }
        if(Mat.Material__c == null)
        {
            msg = '物料不能为空';
            Mat.AllocatedNumber__c = total;
            total=0;
            return null;
        } 
        if(Mat.Total_Number__c == null)
        {
            msg = '物料总数不能为空';
            Mat.AllocatedNumber__c = total;
            total=0;
            return null;
        }         
        if(total  > Mat.Total_Number__c)
        {
            msg = '已分配数超过物料总数';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }   
        if(Mat.Materical_Start_Date__c > Mat.Materical_End_Date__c)
        {
            msg = '开始日期不能晚于结束日期';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }     
        if(Mat.Materical_Start_Date__c<= date.today())
        {
            msg = '开始日期需选择明天及以后';
            Mat.AllocatedNumber__c = total;
            total = 0;
            return null;
        }              
        if(total  < Mat.Total_Number__c)
        {
            msg1 = '分配量小于物料总量，保存成功';
        }  
        Boolean haveNum = false;
        for(HospitalMaterial__c hm : HosMatList)
        {
            if((hm.Number__c != 0)&&(hm.Number__c != null))
            {
                haveNum = false;
            }
            else
            {
                haveNum = true;
                break;
            }            
        }
        if(!haveNum)
        {
            msg = '未填写医院分配物料数';
            return null;
        }
        
        Mat.Name = string.valueof(Mat.Materical_Start_Date__c) + Mat.Material__c  + '物料分配';
        Mat.AllocatedNumber__c = total;
        update Mat;
        
        List<HospitalMaterial__c> insertList = new List<HospitalMaterial__c>();
        List<HospitalMaterial__c> updateList = new List<HospitalMaterial__c>();
        List<HospitalMaterial__c> delList = new List<HospitalMaterial__c>();
        
        for(HospitalMaterial__c hm : HosMatList)
        {

            if((hm.Number__c != 0)&&(hm.Number__c != null)){
                hm.Name = String.valueof(Mat.Materical_Start_Date__c)+hm.name + '物料分配';
                if(hm.CreatedDate != null)
                {
                    Material__Share mShare = new Material__Share();
                    mShare.ParentId = Mat.id;
                    mShare.UserOrGroupId = hm.ownerid;
                    mShare.AccessLevel = GlobalProperties.ReadPermission;
                    MatShare.add(mShare); 
                                                                
                    updateList.add(hm);
                }
                else{
                    hm.Material__c = Mat.id;
                    
                    Material__Share mShare = new Material__Share();
                    mShare.ParentId = Mat.id;
                    mShare.UserOrGroupId = hm.ownerid;
                    mShare.AccessLevel = GlobalProperties.ReadPermission;
                    MatShare.add(mShare);     
                                    
                    insertList.add(hm);
                }
            }
            if((hm.Number__c == 0)||(hm.Number__c == null))
            {
                if(hm.CreatedDate != null)
                {
                    delList.add(hm);
                }
            }
        }
        insert insertList;
        update updateList;
        delete delList;
        
        Set<id> MsrIds = new Set<id>();
        for(HospitalMaterial__c hm : insertList)
        {
            MsrIds.add(hm.ownerid);
            
        }
        for(HospitalMaterial__c hm : updateList)
        {
            MsrIds.add(hm.ownerid);
            
        }
        for(HospitalMaterial__c hm : delList)
        {
            MsrIds.add(hm.ownerid);
            
        }                
        List<User> MsrList = [Select id,Email,Alias From User Where id in: MsrIds];
        for(User u : MsrList)
        {
            List<String> toAddresses = new List<String>();
            toAddresses.add( u.Email );  
            List<String> ccAddresses = new List<String>();
            String Body = '您好！\n' + '您的物料管理"' + Mat.Name +'"已更新! \n' + string.valueof(Date.Today());
            String Subject = '物料管理';
                    
            EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);        
            
        }
               
        
        List<Material__Share> MatList = new List<Material__Share>();
        for(Material__Share m : MatShare)
        {
            MatList.add(m);
        }
        if(MatList.size() > 0)
            insert MatList;
        
        PageReference pr=new PageReference('/'+urlid);
        pr.setRedirect(true);
        return pr;
    }

    public PageReference Cancel()
    {

        PageReference pr=new PageReference('/'+urlid);
        pr.setRedirect(true);
        return pr;
    }
    private final ApexPages.StandardController controller;
    
    static testMethod void OverrideViewTest()
    {
        Material__c add = new Material__c();
        add.name = 'test';
        add.Date__c = date.today();
        insert add;
        
        System.currentPageReference().getParameters().put('id', add.Id); 
        
        ApexPages.StandardController del = new ApexPages.StandardController(add);
        
        OverrideMaterialEdit testCase = new OverrideMaterialEdit(del);
        testCase.Save();
        testCase.Cancel();    
    }
 
}